import java.math.BigDecimal;

public class 字符串相乘 {
    /**
     * https://leetcode.cn/problems/multiply-strings/description/
     */

    //方法一调用封装的方法
    public static String multiply(String num1, String num2) {
        BigDecimal bigDecimal = new BigDecimal(num1);
        bigDecimal = bigDecimal.multiply(new BigDecimal(num2));
        return bigDecimal.toString();
    }
    public static int MAXN = 400;//最大的相乘长度
    public static int[] str = new int[MAXN + 1];//防止溢出加一
    public static int cnt = MAXN;//指针判断乘的时候要乘哪里
    //手写一个字符串相乘
    public static String multiply1(String num1, String num2) {
        //为0直接返回
        if("0".equals(num1) || "0".equals(num2)){
            return "0";
        }
        //转成字符数组好操作
        char[] nums1 = num1.toCharArray();
        char[] nums2 = num2.toCharArray();
        //123 456 操作6乘123每一个数
        for (int i = nums2.length - 1; i >= 0; i--) {
            int a = nums2[i] - '0';
            int cnt1 = cnt;//操作要变位添加
            for (int j = nums1.length - 1; j >= 0; j--) {
                int b = a * (nums1[j] - '0') + str[cnt1];
                if(b / 10 != 0){
                    str[cnt1] = b % 10;
                    str[cnt1 - 1] += b / 10;
                }else {
                    str[cnt1] = b;
                }
                cnt1--;//每次操作往前进一位
            }
            cnt--;//一行乘完进位
        }
        //找到不为0的开头
        for (int i = 0; i <= MAXN; i++) {
            if(str[i] != 0){
                cnt = i;
                break;
            }
        }
        StringBuilder sb = new StringBuilder();

        for (int i = cnt; i <= MAXN; i++) {
            sb.append(str[i]);
        }
        return sb.toString();
    }
    public static void main(String[] args) {
        System.out.println(multiply("123", "456"));
        System.out.println(multiply1("123", "456"));

    }
}
